package sniper.popup.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.ITextEditor;

import sniper.targets.SnippetHolder;
import sniper.wizard.SniperWizard;

public class SniperAction implements IEditorActionDelegate {
	
	private ISelection selection;
	private IWorkbenchPart part;
	private ITextEditor textEditor;
	
	
	/**
	 * Constructor for Action1.
	 */
	public SniperAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.part = targetPart;
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		Shell shell = new Shell();

		//Instantiates and initializes the wizard
		SniperWizard wizard = new SniperWizard();
		if ((selection instanceof IStructuredSelection) || (selection == null))
		wizard.init(part.getSite().getWorkbenchWindow().getWorkbench(), 
			(IStructuredSelection)selection);
			
		// Instantiates the wizard container with the wizard and opens it
		WizardDialog dialog = new WizardDialog(shell, wizard);
		dialog.create();
		dialog.open();
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart)
	 */
	public void setActiveEditor(IAction action, IEditorPart targetEditor) {
		
		this.textEditor = (ITextEditor) targetEditor;
		IDocument document =
			textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
		ITextSelection ts =
			(ITextSelection) textEditor.getSelectionProvider().getSelection();
		
		String snippet = "";
		try {
			
			snippet = document.get(ts.getOffset(), ts.getLength());
		} catch (BadLocationException e) {
			
			e.printStackTrace();
		}
		
		SnippetHolder.setSNIPPET(snippet);
		
		System.out.println("Text Selected: \n"+snippet);
	}

}
